package com.wulinbus.controller;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.List;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.simple.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CookieValue;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import com.fancy.common.StoreFileTypeEnum;
import com.fancy.common.results.Results;
import com.fancy.common.utils.Config;
import com.fancy.common.utils.StringUtil;
import com.wulinbus.model.UserModel;
import com.wulinbus.service.FileStoreService;
import com.wulinbus.service.UserService;
import com.wulinbus.utils.CasUtil;

/**
 * 文件上传下载接口
 */
@Controller
@RequestMapping(value = "/common")
public class CommonController {
	
	@Resource
	private UserService userService;
	
	@Resource
	private FileStoreService fileStoreService;
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "upload.json", method = RequestMethod.POST )
	public void upload(String uploadflag,@CookieValue(value="muid",defaultValue="") String muid,Model model,HttpServletRequest request,@RequestParam("dir")String fileType,@RequestParam(defaultValue="false")Boolean fromEditor,HttpServletResponse response,@RequestParam("imgFile")MultipartFile file) throws IOException{
		response.setContentType("text/html; charset=UTF-8");
		String uid=CasUtil.getUid(request);
		if(StringUtil.isEmpty(uid)&&StringUtil.isEmpty(muid))
			return;
		Results<String> fileUploadDO;
		try {
			fileUploadDO = fileStoreService.saveFile(uploadflag,file, StoreFileTypeEnum.getType(fileType).toString(),uid);
			if (fileUploadDO.isSuccess()) {
				JSONObject obj = new JSONObject();
				obj.put("error", 0);
				obj.put("url", Config.getString("upload.file.host")+fileUploadDO.getObject());
				response.getWriter().println(obj.toJSONString());
			}else {
				response.getWriter().println(getError(fileUploadDO.getMessage()));
				return;
			}
		} catch (Exception e) {
			e.printStackTrace();
			response.getWriter().println(getError(e.getMessage()));
		}	
	}
	
	@SuppressWarnings("unchecked")
	@RequestMapping(value = "upload_manager.json", method = {RequestMethod.GET,RequestMethod.POST} )
	public void upload_manager(Model model,@RequestParam("dir")String filetype,HttpServletRequest request,HttpServletResponse response) throws IOException{
		String uid = CasUtil.getUid(request);
		String rootPath = Config.getString("upload.file.root","/");
		String rootUrl = Config.getString("upload.file.host","");
        
		String[] fileTypes = new String[]{"gif", "jpg", "jpeg", "png", "bmp","doc"};

		//根据path参数，设置各路径和URL
		String path = request.getParameter("path") != null ? request.getParameter("path") : "";
		String currentPath = rootPath +uid+"/"+ path;
		String currentUrl = rootUrl+uid+"/" + path;
		String currentDirPath = path;
		String moveupDirPath = "";
		if (!"".equals(path)) {
			String str = currentDirPath.substring(0, currentDirPath.length() - 1);
			moveupDirPath = str.lastIndexOf("/") >= 0 ? str.substring(0, str.lastIndexOf("/") + 1) : "";
		}

		//排序形式，name or size or type
		String order = request.getParameter("order") != null ? request.getParameter("order").toLowerCase() : "name";

		//不允许使用..移动到上一级目录
		if (path.indexOf("..") >= 0) {
			response.getWriter().println("Access is not allowed.");
			return;
		}
		//最后一个字符不是/
		if (!"".equals(path) && !path.endsWith("/")) {
			response.getWriter().println("Parameter is not valid.");
			return;
		}
		//目录不存在或不是目录
		File currentPathFile = new File(currentPath);
		if(!currentPathFile.isDirectory()){
			response.getWriter().println("Directory does not exist.");
			return;
		}

		//遍历目录取的文件信息
		List<Hashtable<String,Object>> fileList = new ArrayList<Hashtable<String,Object>>();
		if(currentPathFile.listFiles() != null) {
			for (File file : currentPathFile.listFiles()) {
				Hashtable<String, Object> hash = new Hashtable<String, Object>();
				String fileName = file.getName();
				if(file.isDirectory()) {
					hash.put("is_dir", true);
					hash.put("has_file", (file.listFiles() != null));
					hash.put("filesize", 0L);
					hash.put("is_photo", false);
					hash.put("filetype", "");
				} else if(file.isFile()){
					String fileExt = fileName.substring(fileName.lastIndexOf(".") + 1).toLowerCase();
					hash.put("is_dir", false);
					hash.put("has_file", false);
					hash.put("filesize", file.length());
					hash.put("is_photo", Arrays.<String>asList(fileTypes).contains(fileExt));
					hash.put("filetype", fileExt);
				}
				hash.put("filename", fileName);
				hash.put("datetime", new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(file.lastModified()));
				fileList.add(hash);
			}
		}

		if ("size".equals(order)) {
			Collections.sort(fileList, new SizeComparator());
		} else if ("type".equals(order)) {
			Collections.sort(fileList, new TypeComparator());
		} else {
			Collections.sort(fileList, new NameComparator());
		}
		JSONObject result = new JSONObject();
		result.put("moveup_dir_path", moveupDirPath);
		result.put("current_dir_path", currentDirPath);
		result.put("current_url", currentUrl);
		result.put("total_count", fileList.size());
		result.put("file_list", fileList);

		response.setContentType("application/json; charset=UTF-8");
		response.getWriter().println(result.toJSONString());
		
	}
	
	@SuppressWarnings("rawtypes")
	class NameComparator implements Comparator {
		@Override
		public int compare(Object a, Object b) {
			Hashtable hashA = (Hashtable)a;
			Hashtable hashB = (Hashtable)b;
			if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) {
				return -1;
			} else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) {
				return 1;
			} else {
				return ((String)hashA.get("filename")).compareTo((String)hashB.get("filename"));
			}
		}
	}
	@SuppressWarnings("rawtypes")
	class SizeComparator implements Comparator {
		@Override
		public int compare(Object a, Object b) {
			Hashtable hashA = (Hashtable)a;
			Hashtable hashB = (Hashtable)b;
			if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) {
				return -1;
			} else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) {
				return 1;
			} else {
				if (((Long)hashA.get("filesize")) > ((Long)hashB.get("filesize"))) {
					return 1;
				} else if (((Long)hashA.get("filesize")) < ((Long)hashB.get("filesize"))) {
					return -1;
				} else {
					return 0;
				}
			}
		}
	}
	@SuppressWarnings("rawtypes")
	class TypeComparator implements Comparator {
		@Override
		public int compare(Object a, Object b) {
			Hashtable hashA = (Hashtable)a;
			Hashtable hashB = (Hashtable)b;
			if (((Boolean)hashA.get("is_dir")) && !((Boolean)hashB.get("is_dir"))) {
				return -1;
			} else if (!((Boolean)hashA.get("is_dir")) && ((Boolean)hashB.get("is_dir"))) {
				return 1;
			} else {
				return ((String)hashA.get("filetype")).compareTo((String)hashB.get("filetype"));
			}
		}
	}
	
	@SuppressWarnings("unchecked")
	private String getError(String message) {
		JSONObject obj = new JSONObject();
		obj.put("error", 1);
		obj.put("message", message);
		return obj.toJSONString();
	}
	
	@RequestMapping(value = "getUserName.json", method = RequestMethod.POST )
	public void getUserName(Model model,String uid){
		if(!StringUtil.isEmpty(uid)){
			UserModel userModel = userService.findUserByUid(Integer.parseInt(uid));
			model.addAttribute("name", userModel.getComp());
		}
		else{
			model.addAttribute("name", "");
		}
	}
}
